/**
 * 
 */
package design_pattern.singleton;

/**
 * 与当前线程相关的线程本地化的单例模式
 * 
 * @author linzq
 * 
 */
public class SingletonTheadSafeThreadLocal {

  private static SingletonTheadSafeThreadLocal instance = null;

  private static ThreadLocal<SingletonTheadSafeThreadLocal> local =
          new ThreadLocal<>();

  private SingletonTheadSafeThreadLocal() {}

  /**
   * 线程本地化的单例
   * 
   * @return
   */
  public static SingletonTheadSafeThreadLocal getInstance() {
    // 使用ThreadLocal取得实例，如果本地化实例不存在就创建一个实例，并放到ThreadLocal中。
    instance = local.get();
    if (instance == null) {
      instance = new SingletonTheadSafeThreadLocal();
      local.set(instance);
    }
    return instance;
  }

}
